/*************************************************************************
 * This file is part of HeroesForge.
 *
 * HeroesForge is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * HeroesForge is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with HeroesForge.  If not, see <http://www.gnu.org/licenses/>.
 *************************************************************************/
package org.diskordia.heroesforge.console.threading;

import org.diskordia.heroesforge.client.IClientContext;
import org.diskordia.heroesforge.client.preferences.IConnectionInfo;
import org.diskordia.heroesforge.console.IMainView;
import org.diskordia.heroesforge.core.security.SessionInfo;
import org.diskordia.heroesforge.core.service.IHeroesForgeService;
import org.jdesktop.application.Application;
import org.jdesktop.application.Task;

import com.google.inject.Inject;

/**
 * @author lehmamic
 */
public class AuthenticateTask extends Task<SessionInfo, Void> {
	
	private IClientContext clientContext;
	private IMainView mainView;
	
	/**
	 * Initializes an instance of the @see AuthenticateSwingWorker class.
	 *
	 * @param application
	 */
	@Inject
	public AuthenticateTask(Application application, IClientContext context, IMainView view) {
		super(application);
		
		if(context == null)
		{
			throw new IllegalArgumentException("The context instance is a null reference.");
		}
		
		if(view == null)
		{
			throw new IllegalArgumentException("The view instance is a null reference.");
		}
		
		this.clientContext = context;
		this.mainView = view;
	}

	/* (non-Javadoc)
	 * @see javax.swing.SwingWorker#doInBackground()
	 */
	@Override
	protected SessionInfo doInBackground() throws Exception {
		SessionInfo session = null;
		
		try
		{
			this.setConnectActionEnabled(false);
			
			IConnectionInfo ci = this.clientContext.getPreferences().getServerConnection();
			
			IHeroesForgeService service = this.clientContext.getServiceProxy();
			session = service.Authenticate(ci.getUserName(), ci.getPassword());
			
			this.succeeded(session);
		}
		catch(Exception e)
		{
			this.failed(e);
		}
		finally
		{
			this.setConnectActionEnabled(true);
		}
		
		return session;
	}
	
	private void setConnectActionEnabled(boolean enabled)
	{
		this.mainView.setConnectActionEnabled(enabled);
	}
}
